/**
 * Created by udi on 17-4-11.
 */


import "./markdown.js"

var api_markdown = function (list, level, example) {
	const get_headers = function (headers) {
		if (!headers || !headers.length) {
			return "";
		}

		const get_header = function (header) {
			return `| ${header.key}      | ${header.remark}       |  ${header.required ? '必填' : ''}  |`
		}

		return `**请求头**
| 参数名       |    备注      |  是否必填  |
| ----------- | ----------- | -------- |
${headers.map(it => get_header(it)).join("\n")}`
	}

	const get_param1 = function (param) {
		return `| ${param.key}      | ${param.remark}       |  ${param.in_path ? '路径参数,必填!' : (param.required ? '必填' : '')}  |`

	}

	const get_params = function (def) {
		var params = Object.assign([], def.requestUrlPathParameters);
		params.forEach(it => {
			it.in_path = true;
		});

		params.addAll(def.requestUrlQueryParameters);


		if (!params.length) {
			return "";
		}


		return `**请求参数**
| 参数名       |    备注    |  是否必填 |
| ----------- | ----------- | ----------- |
${params.map(it => get_param1(it)).join("\n")}`
	}

	const get_file = function (def) {
		if(!def.uploadFileName){
			return ""
		}


		return `**文件上传**
要求请求头 content-type: multipart/form-data
请求参数名: \`${def.uploadFileName}\`

`
	}

	const proc_json = function (json, list, deepth) {
		if (!json || !json.length) {
			return;
		}

		json.forEach(it => {
			const key = it.key;
			var remark = (it.remark || "").replaceAll("\n", "<br />")
			if (it.type == "Enum") {
				remark += "<br />枚举项: <br />" + it.enumData.join(",<br />") + ";";
			}

			if (it.isList) {
				list.push({name: key, type: it.type + "[]", deepth: deepth, desc: remark});
				proc_json(it.items, list, deepth + 1);
			} else if (it.type == "Object") {
				list.push({name: key, type: it.type, deepth: deepth, desc: remark});
				proc_json(it.items, list, deepth + 1);
			} else {
				list.push({name: key, type: it.type, deepth: deepth, desc: remark});
			}
		})
	}

	const get_row = function (row, max_level) {
		var ret = [];
		for (var i = 1; i <= max_level; i++) {
			if (row.deepth == i) {
				ret.push(row.name)
			} else {
				ret.push("   ");
			}
		}

		ret.push(row.type);
		ret.push(row.desc);


		return "| " + ret.join(" | ") + " |";
	}

	const get_response = function (json) {
		if (!json) {
			return "";
		}

		const list = [];
		proc_json(json.items, list, 1)

		const max_level = list.map(it => it.deepth).max();

		if (!list.length) {
			return "";
		}

		var levels = [];
		for (var i = 2; i <= max_level; i++) {
			levels.push("  " + i + "级参数");
		}
		return `**响应数据**
| 参数名  |  ${levels.map(it => it + "  |").join("")}   类型     |   备注    |
| --- | ${levels.map(it => " --- | ").join("")} --- | --- |
${list.map(it => get_row(it, max_level)).join("\n")}`
	}


	const get_request_body = function (json) {
		if (!json) {
			return "";
		}

		const list = [];

		proc_json(json.items, list, 1)
		const max_level = list.map(it => it.deepth).max();


		if (!list.length) {
			return "";
		}

		var levels = [];
		for (var i = 2; i <= max_level; i++) {
			levels.push("  " + i + "级参数");
		}


		return `**请求数据${json.isList ? " -- 数组[]" : ""}**
| 参数名  |  ${levels.map(it => it + "  |").join("")}   类型     |   备注    |
| --- | ${levels.map(it => " --- | ").join("")} --- | --- |
${list.map(it => get_row(it, max_level)).join("\n")}`
	}

	const sp_json_default_values = {
		Int: {
			pageNo: 1,
			pageSize: 10
		},
		Boolean: {
			success: true
		}
	}
	const get_sp_json = function (def) {
		//根据def定义生成Json示例！

		if (def.items && !def.items.length) {
			return "";
		}

		var ret = {};
		for (var i = 0, len = def.items.length; i < len; i++) {
			var item = def.items[i];
			var value = "";
			if (item.type == "Object") {
				value = get_sp_json(item)
			} else {
				if (item.type == "Int") {
					value = sp_json_default_values.Int[item.key] || 0;
				} else if (item.type == "Boolean") {
					value = sp_json_default_values.Boolean[item.key] || false;
				}

				if (item.isList) {
					value = [value];
				}
			}

			ret[item.key] = value;
		}

		if (def.isList) {
			ret = [ret];
		}
		return ret;
	}

	const get_sp = function (def) {
		if (!example) {
			return "";
		}

		var query = def.requestUrlQueryParameters.map(it => it.key + "=").join("&");
		if (query) {
			query = "?" + query;
		}

		var header = def.requestHeaderParameters.map(it => it.key + ": ").join("\n");
		if (header) {
			header = "\n" + header + "\n";
		}
		var requestBody = get_sp_json(def.requestBodyParameters);
		if (Object.keys(requestBody).length) {
			requestBody = `
${JSON.stringify(requestBody, null, 4)}`
		} else {
			requestBody = "";
		}

		var responseBody = get_sp_json(def.responseBodyParameters);

		return "接口示例：\n" +
			"```json\n" +
			`${def.httpMethod} ${def.url}${query}
请求头: ${header || "无"}
请求体: ${requestBody || "无"}
响应体:
${JSON.stringify(responseBody, null, 4)}
`
			+ "\n```";
	}

	const api_markdown1 = function (def, level) {
		var remark = def.remark;
		if (remark) {
			remark += "\n"
		}

		var ret = `
${"#".repeat(level)} ${def.name}
\`${def.httpMethod}\` \`${def.url}\`
${remark}
` + [
			get_headers(def.requestHeaderParameters),
			get_params(def),
			get_file(def),
			get_request_body(def.requestBodyParameters),
			get_response(def.responseBodyParameters),
			get_sp(def)
		].filter(it => it).join("\n\n")

		return ret;
	}


	var txts = [];
	var productLines = list
		.map(it => it.productLine.name + "\t" + it.app)
		.distinct()
		.sort();


	var genGroupApis = (groupApis, level) => {
		var txts = [];

		txts.push(`**接口概览**`)
		txts.push(`|   序号   |   接口名称  |   请求方法   |  接口地址  |
| ------- |----------- | ---------- | --------- |`)
		var index = 0;
		txts.addAll(groupApis.map(it => {
			return `| ${++index} |  ${it.name} | ${it.httpMethod}  | ${it.url}  |`
		}));
		txts.addAll(groupApis.map(it => api_markdown1(it, level + 1)));
		return txts;
	}

	productLines.forEach(productLineApp => {
		var sect = productLineApp.split("\t")
		var productLine = sect[0];
		var app = sect[1];

		txts.push("#".repeat(level) + " " + productLine + "-" + app)

		var productLineApis = list.filter(it => it.productLine.name == productLine && it.app == app);

		productLineApis.forEach(it => {
			var groupFullName = it.group
			var sects = groupFullName.split("--");
			if (sects.length) {
				it.group1 = sects[0];
				it.group2 = groupFullName;
			} else {
				it.group1 = groupFullName;
			}
		})

		var groups1 = productLineApis.map(it => it.group1)
			.distinct()
			.sort();

		groups1.forEach(group1Name => {
			txts.push("#".repeat(level + 1) + " " + group1Name)

			var groups2 = productLineApis.filter(it => (it.group1 == group1Name) && it.group2)
				.map(it => it.group2)
				.distinct()
				.sort();

			if (groups2.length && groups2.length > 1) {
				txts.push(`**子模块列表**`)
				txts.push(`|   序号   |   子模块名称  |
| ------- |----------- |`)

				var index = 0;
				txts.addAll(groups2.map(it => `| ${++index} | ${it} |`))
			}

			var group1Apis = productLineApis.filter(it => it.group1 == group1Name && !it.group2)

			if (group1Apis.length) {
				txts.addAll(genGroupApis(group1Apis, level));
			}

			if (groups2.length && groups2.length > 1) {
				groups2.forEach(groupName => {
					txts.push("#".repeat(level + 2) + " " + groupName)
					var group2Apis = productLineApis.filter(it => it.group1 == group1Name && it.group2 == groupName)

					txts.addAll(genGroupApis(group2Apis, level + 2));
				})
			} else {
				groups2.forEach(groupName => {
					var group2Apis = productLineApis.filter(it => it.group1 == group1Name && it.group2 == groupName)

					txts.addAll(genGroupApis(group2Apis, level + 2));
				})
			}
		})
	})

	return "生成时间 `" + Date.nowString("yyyy-MM-dd HH:mm") + "`\n\n" + txts.join("\n");
}

export default api_markdown
